<template>
  <div v-loading="loading">
    <el-row :gutter="20">
      <template v-for="item in detailsList">
        <el-col :key="item.code" :span="item.span">
          <div class="box" :style="{ backgroundImage: 'url(' + item.bgImg + ')' }" @click="jumpRoute(item.code)">
            <div class="box_margin">
              <p class="gl_mb_5 gl_fs_14">
                <span class="gl_mb_5" style="display: block;">{{ item.name }}</span>
                <template class="certificate">
                  <img v-if="item.code == 'TrainingCertificate'" src="@/assets/images/mall/证件模版icon.svg" alt="">
                </template>
              </p>
              <p v-if="item.code != 'TrainingCertificate'" :style="{ color: item.color }">{{ item.sum ? item.sum : 0 }}</p>
            </div>
          </div>
        </el-col>
      </template>
    </el-row>
    <div class="gl_mt_20">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="details_box">
            <div>
              <BarChart :default-data="TrainPeople" :width="barWidth" :height="barHeight" />
            </div>
            <div v-if="TrainPeople.series[0].data.length < 1" class="no_echart">暂无数据</div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="details_box">
            <div>
              <BarChart :default-data="ExamPeople" :width="barWidth" :height="barHeight" />
            </div>
            <div v-if="ExamPeople.series[0].data.length < 1" class="no_echart">暂无数据</div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import BarChart from './components/BarChart';
import {
  api_GET_TrainTrainningEntryDataTrainningEntryDataStatisticsTrainningId
} from '@/extend/api/trainswaggerApi/app.js';

export default {
  components: {
    BarChart
  },
  data() {
    return {
      loading: false,
      barWidth: '100%',
      barHeight: '540px',
      detailsList: [
        {
          code: 'TrainingAmount',
          name: '培训金额（元）',
          sum: 0,
          span: 6,
          color: '#c10000',
          bgImg: require('@/assets/images/mall/statistics_bg_1.png'),
          isShow: true
        },
        {
          code: 'Personnel',
          name: '人员数据统计（人）',
          sum: 0,
          span: 6,
          color: '#cd7d00',
          bgImg: require('@/assets/images/mall/statistics_bg_2.png'),
          isShow: true
        },
        {
          code: 'TrainLogisticOrder',
          name: '后勤金额（元）',
          sum: 0,
          span: 6,
          color: '#71bd00',
          bgImg: require('@/assets/images/mall/statistics_bg_3.png'),
          isShow: true
        },
        {
          code: 'TrainingCertificate',
          name: '参训证',
          sum: 0,
          span: 6,
          color: '#06b5b5',
          bgImg: require('@/assets/images/mall/statistics_bg_4.png'),
          isShow: true
        }
      ],
      TrainPeople: { // 培训科目参训人数数据
        title: {
          text: '培训科目',
          textStyle: {
            color: '#333',
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          backgroundColor: '#fff',
          textStyle: {
            color: '#595959'
          },
          extraCssText: 'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.15)',
          padding: [8, 16],
          borderRadius: 3
        },
        color: ['#1c92ff'],
        grid: { // 绘图网格
          left: '-20%',
          right: '6%',
          bottom: '3%',
          containLabel: true // 是否包含刻度标签
        },
        xAxis: {
          type: 'value',
          minInterval: 1, // 保证坐标轴分割刻度显示成整数
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          splitLine: { // grid分隔线
            show: false
          },
          axisLabel: { // 刻度标签
            color: '#595959'
          }
        },
        yAxis: {
          type: 'category',
          boundaryGap: [0, 0.01],
          axisLine: { // 坐标轴线
            show: true,
            lineStyle: {
              color: '#E8E8E8'
            }
          },
          splitLine: { // grid分隔线
            show: true,
            lineStyle: {
              type: 'dashed',
              color: ['#E8E8E8']
            }
          },
          splitArea: { // grid分隔区域
            show: false
          },
          axisTick: { // 坐标轴刻度
            show: false,
            alignWithLabel: true // 刻度与标签对齐
          },
          axisLabel: { // 刻度标签
            show: true,
            color: '#595959',
            fontSize: 14,
            align: 'left',
            margin: 180,
            formatter: function(val) {
              let newVal = '';
              let realLength = 0;
              let charCode = -1;
              for (let i = 0; i < val.length; i++) {
                charCode = val.charCodeAt(i);
                if (charCode >= 0 && charCode <= 128) {
                  realLength += 1;
                } else {
                  realLength += 2;
                }
              }
              if (realLength > 20) {
                let char_length = 0;
                for (let j = 0; j < val.length; j++) {
                  const son_str = val.charCodeAt(j);
                  if (son_str >= 0 && son_str <= 128) {
                    char_length += 1;
                  } else {
                    char_length += 2;
                  }
                  if (char_length >= 20) {
                    newVal = val.substr(0, j + 1) + '...';
                    break;
                  }
                }
                return newVal;
              } else {
                return val;
              }
            }
          },
          data: []
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            barWidth: 24,
            data: []
          }
        ]
      },
      ExamPeople: { // 考试科目参训人数数据
        title: {
          text: '考试科目',
          textStyle: {
            color: '#333',
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          backgroundColor: '#fff',
          textStyle: {
            color: '#595959'
          },
          extraCssText: 'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.15)',
          padding: [8, 16],
          borderRadius: 3
        },
        color: ['#ffbd3e'],
        grid: { // 绘图网格
          left: '-20%',
          right: '6%',
          bottom: '3%',
          containLabel: true // 是否包含刻度标签
        },
        xAxis: {
          type: 'value',
          minInterval: 1, // 保证坐标轴分割刻度显示成整数
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          splitLine: { // grid分隔线
            show: false
          },
          axisLabel: { // 刻度标签
            color: '#595959'
          }
        },
        yAxis: {
          type: 'category',
          boundaryGap: [0, 0.01],
          axisLine: { // 坐标轴线
            show: true,
            lineStyle: {
              color: '#E8E8E8'
            }
          },
          splitLine: { // grid分隔线
            show: true,
            lineStyle: {
              type: 'dashed',
              color: ['#E8E8E8']
            }
          },
          splitArea: { // grid分隔区域
            show: false
          },
          axisTick: { // 坐标轴刻度
            show: false,
            alignWithLabel: true // 刻度与标签对齐
          },
          axisLabel: { // 刻度标签
            show: true,
            color: '#595959',
            fontSize: 14,
            align: 'left',
            margin: 180,
            formatter: function(val) {
              let newVal = '';
              let realLength = 0;
              let charCode = -1;
              for (let i = 0; i < val.length; i++) {
                charCode = val.charCodeAt(i);
                if (charCode >= 0 && charCode <= 128) {
                  realLength += 1;
                } else {
                  realLength += 2;
                }
              }
              if (realLength > 20) {
                var char_length = 0;
                for (let j = 0; j < val.length; j++) {
                  var son_str = val.charCodeAt(j);
                  if (son_str >= 0 && son_str <= 128) {
                    char_length += 1;
                  } else {
                    char_length += 2;
                  }
                  if (char_length >= 20) {
                    newVal = val.substr(0, j + 1) + '...';
                    break;
                  }
                }
                return newVal;
              } else {
                return val;
              }
            }
          },
          data: []
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            barWidth: 24,
            data: []
          }
        ]
      }
    };
  },
  created() {
    this.getData();
    this.getExam();
  },
  methods: {
    // 获取数据管理首页数据
    getData() {
      var that = this;
      that.loading = true;
      const trainningId = this.$route.params.id;
      const form = {
        IsAmount: true,
        IsRegisterCount: true,
        IsLogisticsAmount: true,
        IsSubjectEntryRegisters: true,
        SubjectTypeCode: 'Train'
      };
      api_GET_TrainTrainningEntryDataTrainningEntryDataStatisticsTrainningId(trainningId, form).then(res => {
        that.detailsList[0].sum = res.amount ? that.formatMoney(res.amount) : '0.00';
        that.detailsList[1].sum = res.registerCount;
        that.detailsList[2].sum = res.logisticsAmount ? that.formatMoney(res.logisticsAmount) : '0.00';
        // 培训科目参训人数
        const subjectEntryRegisters = res.subjectEntryRegisters || [];
        const subject = that.handleSubjectRegisters(subjectEntryRegisters);
        that.TrainPeople.yAxis.data = subject.yAxis;
        that.TrainPeople.series[0].data = subject.xAxis;

        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error && error.error.message });
      });
    },
    getExam() {
      var that = this;
      that.loading = true;
      const trainningId = this.$route.params.id;
      const form = {
        IsAmount: false,
        IsRegisterCount: false,
        IsLogisticsAmount: false,
        IsSubjectEntryRegisters: true,
        SubjectTypeCode: 'Exam'
      };
      api_GET_TrainTrainningEntryDataTrainningEntryDataStatisticsTrainningId(trainningId, form).then(res => {
        // 考试科目参训人数
        const subjectEntryRegisters = res.subjectEntryRegisters || [];
        const subject = that.handleSubjectRegisters(subjectEntryRegisters);
        that.ExamPeople.yAxis.data = subject.yAxis;
        that.ExamPeople.series[0].data = subject.xAxis;

        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error && error.error.message });
      });
    },
    // 处理科目参训人数
    handleSubjectRegisters(subject) {
      const obj = {
        xAxis: [],
        yAxis: []
      };
      for (var i = 0; i < subject.length; i++) {
        var item = subject[i];
        obj.xAxis.push(item.registerCount);
        obj.yAxis.push(item.subjectName);
      }
      return obj;
    },
    // 跳转详情
    jumpRoute(code) {
      // const { query } = this.$route;
      this.$router.push({
        name: code
        // query: {
        //   gameName: query.gameName || ''
        // }
      });
    },
    subString(str, len, hasDot) {
      var newLength = 0;
      var newStr = '';
      var chineseRegex = /[^\x00-\xff]/g;
      var singleChar = '';
      var strLength = str.replace(chineseRegex, '**').length;
      for (var i = 0; i < strLength; i++) {
        singleChar = str.charAt(i).toString();
        if (singleChar.match(chineseRegex) != null) {
          newLength += 2;
        } else {
          newLength++;
        }
        if (newLength > len) {
          break;
        }
        newStr += singleChar;
      }

      if (hasDot && strLength > len) {
        newStr += '...';
      }
      return newStr;
    },
    getStrLength(str) {
      // 中文长度为2，英文长度为1
      let long = 0;
      for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
          long += 2;
        } else {
          long++;
        }
      }
      return long;
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.details_box {
  border-radius: 4px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.09);
  padding: 20px;
  min-width: 260px;
  position: relative;
}
.box {
  width: 100%;
  height: 114px;
  background-repeat: no-repeat;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.09);
  background-size: 100% 100%;
  color: #8C8A8A;
  font-size: 30px;
  display: inline-block;
  cursor: pointer;
  transition: all .5s ease 0s;
}
.box_margin {
  margin: 26px;
}
.box:hover {
  transform: scale(1.1);
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.09);
}
.sum {
  font-size: 28px;
  font-weight: bold;
}
.name {
  font-size: 14px;
  font-weight: 500;
}
.certificate {
  display: block;
}
.no_echart {
  width: 100%;
  height: 540px;
  line-height: 540px;
  text-align: center;
  color: #515a6e;
  font-size: 12px;
  position: absolute;
  top: 6px;
  left: 0;
  z-index: 99;
  background: #fff;
}
</style>
